const Router = require("@koa/router")
const router = new Router()
const fileModel = require("../model/File")
const to = require("await-to-js").default

router.get("/getFile", async (ctx) => {
  var [err, files] = await to(
    fileModel.findAll({
      attributes: { exclude: ["content"] },
    })
  )
  if (err) {
    ctx.err("操作失败，请重试", err)
    return
  }
  ctx.suc("操作成功", files)
})

router.post("/addFile", async (ctx) => {
  const params = ctx.request.body
  var [err, files] = await to(fileModel.create(params))
  if (err) {
    ctx.err("操作失败，请重试", err)
    return
  }
  ctx.suc("操作成功", files)
})

router.post("/updateFile", async (ctx) => {
  if (ctx.empty(["fileId"])) {
		return
	}
  const params = ctx.request.body
  var [err] = await to(fileModel.update(params,{
    where:{
      id:params.fileId
    }
  }))
  if (err) {
    ctx.err("操作失败，请重试", err)
    return
  }
  ctx.suc("操作成功")
})

router.get("/getMarkdown", async (ctx) => {
  const params = ctx.query
  var [err, file] = await to(
    fileModel.findByPk(params.id, {
      include: [
        {
          model: require("../model/User"),
          attributes: ["id", "name"],
          required: false,
          as: "user",
        },
        {
          model: require("../model/User"),
          attributes: ["id", "name"],
          required: false,
          as: "occupyUser",
        },
      ],
    })
  )
  if (err) {
    ctx.err("操作失败，请重试", err)
    return
  }
  ctx.suc("操作成功", file)
})

router.post("/updateMarkdown", async (ctx) => {
  if (ctx.empty(["id", "content"])) {
		return
	}
  const params = ctx.request.body
  var [err, file] = await to(
    fileModel.update(
      {
        content: params.content,
      },
      {
        where: {
          id: params.id,
        },
      }
    )
  )
  if (err) {
    ctx.err("操作失败，请重试", err)
    return
  }
  ctx.suc("操作成功", file)
})

router.post("/dltFile", async (ctx) => {
  const params = ctx.request.body
  var [err, file] = await to(
    fileModel.destroy({
      where: {
        id: {
          [Op.or]:params.idArr},
      },
    })
  )
  if (err) {
    ctx.err("操作失败，请重试", err)
    return
  }
  ctx.suc("操作成功", file)
})

router.post("/uploadFile", async (ctx) => {
  const upload = require("../service/upload")
  var [err, file] = await to(upload(ctx))
  if (err) {
    ctx.err("上传失败", err)
    return
  }
  ctx.suc("上传成功", file.url)
})
module.exports = router.routes()
